<?php
	/*
		This file generates a zipped Java classes file based on the data from the server. It needs the project id and the
		json id of the diagram
	*/
	require_once("../functions.php");
	
	if(!isLoggedIn()){
		die("Please login first.");
	}
	
	date_default_timezone_set("Asia/Manila");
	/**************FUNCTIONS*****************/
	
	function appendCode($text1 = "", $text2 = "", $indent=0){
		$tab = "";
		for($i=0; $i<$indent; $i++){
			$tab = $tab . "\t";
		}
		
		return $text1 . $tab . $text2 . "\n";
	}
	
	function addContentsToZipArchive($zip, $projId, $jsonId){
		$sql = "SELECT c.id, c.name, c.label, c.description FROM component c, diagram d, project p WHERE c.diagram_id=d.id AND d.project_id=p.id AND c.componentType='classBox' AND d.jsonId='$jsonId' AND p.id=$projId";
		$result = mysql_query($sql) or die("Select Classes: " . mysql_error());
		
		while($row = mysql_fetch_array($result)){
			$sql2 = "SELECT c.id,c.jsonId,c.name,c.label,c.diagram_id FROM component c, (SELECT DISTINCT component2_id FROM CONNECTION WHERE component1_id=$row[id]) t WHERE id=component2_id";
			$connectionResult = mysql_query($sql2) or die("get connection: " . mysql_error());
			
			$content = "";
			
			if(mysql_num_rows($connectionResult)>0){
				$connectionRow = mysql_fetch_array($connectionResult);
				$content = "public class $row[label] extends $connectionRow[label]{\n" ;
			}else{
				$content = "public class $row[label]{\n" ;
			}
			
			mysql_free_result($connectionResult);
			
			$sql2 = "SELECT * FROM children WHERE component_id=" . $row["id"] . " ORDER BY TYPE DESC";
			$result2 = mysql_query($sql2) or die("Select children: " . mysql_error());
			
			while($row2 = mysql_fetch_array($result2)){
				if(strcmp($row2["type"], "variable")==0){
					$temp = "$row2[modifier] $row2[childType] $row2[name];";
					$content = appendCode($content, $temp, 1);
				}else if(strcmp($row2["type"], "function")==0){
					$temp = "$row2[modifier] $row2[childType] $row2[name]($row2[parameters]){ }";
					$content = appendCode($content, $temp,1);
				}
			}
			
			$content = $content . "}";
			
			mysql_free_result($result2);
			$zip->addFromString("$row[label].java", $content);
		}
		
		mysql_free_result($result);
	}
	
	/**************END OF FUNCTIONS*****************/
	
	if(!isset($_GET["id"]) || !isset($_GET["jsonId"])){
		die("No parameters");
	}
	
	connectToDb();
	
	$filePath = "class_$_SESSION[username]_project$_GET[id]_$_GET[jsonId].zip";
	$zip = new ZipArchive;
	$zip->open($filePath, ZIPARCHIVE::OVERWRITE) or die("Cannot create the zip file");
	
	addContentsToZipArchive($zip, $_GET["id"], $_GET["jsonId"]);
	
	$zip->close();
	
	header("Content-length: ". filesize($filePath));
	header("Content-type: application/zip");
	header("Content-Disposition: attachment; filename=$filePath");
	ob_clean();
    flush();
    readfile($filePath);
	exit;
?>